package com.zto.tbschedule.console.zookeeper;

import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;

import java.io.UnsupportedEncodingException;

public class FastJsonZKSerializer implements ZkSerializer {
    private static ZkSerializer serializer;
    public static synchronized ZkSerializer getInstance(){
        if(serializer==null){
            serializer = new FastJsonZKSerializer();
        }
        return serializer;
    }
    public byte[] serialize(Object data) throws ZkMarshallingError {
        String json = null;
        if(!(data instanceof String)){
            json=  (String) JSON.toJSON(data);
        }else{
            json = (String) data;
        }
        try {
            return json.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("serializer json:" + json);
        }
    }

    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        try {
            String json = new String(bytes, "UTF-8");
            return json;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("deserialize json:" + bytes);
        }
    }
}
